/*jshint esversion: 9 */
/**
 * color工具
 */

export function randomColor() {  //获取随机颜色
    var rand = Math.floor(Math.random( ) * 0xFFFFFF).toString(16);
    if(rand.length == 6){
        return '#' + rand;
    }else{
        return getRandomColor();
    }
}
export function randomColors(length){  //获取随机颜色列表
    const colors = [];
    while(colors.length < length){
        const color = getRandomColor();
        if(colors.includes(color)) continue;
        colors.push(color);
    }
    return colors;
}
export function isLight(rgb){  //判断颜色是否为亮色
    let rgbValue = rgb.replace("rgb(", "").replace(")", "");
    let rgbValueList = rgbValue.split(',');
    return (rgbValueList[0] * 0.213 + rgbValueList[1] * 0.715 + rgbValueList[2] * 0.072)>(225/2);
}
export function colorRGBtoHex(color) {  //将rgb颜色转换成16进制
    if(!color) return color;
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
}
export function rgbToHex (val) {  //RGB(A)颜色转换为HEX十六进制的颜色值
    var r, g, b, a,
        regRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/,    //判断rgb颜色值格式的正则表达式，如rgba(255,20,10,.54)
        rsa = val.replace(/\s+/g, '').match(regRgba);
    if (!!rsa) {
        r = parseInt(rsa[1]).toString(16);
        r = r.length == 1 ? '0' + r : r;
        g = (+rsa[2]).toString(16);
        g = g.length == 1 ? '0' + g : g;
        b = (+rsa[3]).toString(16);
        b = b.length == 1 ? '0' + b : b;
        a = (+(rsa[5] ? rsa[5] : 1)) * 100;
        return { hex: '#' + r + g + b, r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), alpha: Math.ceil(a) };
    } else {
        return { hex: undefined};
    }
}
export function hexToRgb (val) {   //HEX十六进制颜色值转换为RGB(A)颜色值
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var color = val.toLowerCase();
    var result = '';
    if (reg.test(color)) {
        if (color.length === 4) {
            var colorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
            }
            color = colorNew;
        }
        var colorChange = [];
        for (var i = 1; i < 7; i += 2) {
            colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
        }
        result = "rgb(" + colorChange.join(",") + ")";
        return { rgb: result, r: colorChange[0], g: colorChange[1], b: colorChange[2] };
    } else {
        result = undefined;
        return { rgb: result };
    }
}